<!-- 角色分配资源弹窗内容 -->
<script setup lang="tsx">
import { Descriptions, DescriptionsSchema } from '@/components/Descriptions'
import { PropType, reactive, watch, ref, unref, nextTick, onMounted } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import {
  getMenuListApi,
  sysResourceQueryEpResourceTree,
  sysPermissionSaveRoleResource
} from '@/api/backstage'
import { eachTree, getFirstNode } from '@/utils/tree'

import { clientTypeTreeData } from '@/views/BackstageView/EnterpriseResource/components/index'
import { SUCCESS_CODE } from '@/constants'

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const menuTreeRef = ref<typeof ElTree>()
const menuTreeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}
const defaultCheckedKeys = ref<string[]>([])

const detailSchema = ref<DescriptionsSchema[]>([
  {
    field: 'name',
    label: '角色名称'
  },
  {
    field: 'roleType',
    label: '角色类型'
  }
])

const clientTreeProps = {
  children: 'children',
  label: 'label',
  value: 'id'
}
const clientTreeRef = ref()
const searchParams = ref({
  clientType: 0,
  name: ''
})

const nodeClick = (node: any) => {
  console.log('node', node)
}

const treeData = ref([])
const getMenuList = async () => {
  const res = await sysResourceQueryEpResourceTree({
    clientType: unref(searchParams).clientType,
    roleId: props.currentRow?.id
  })
  if (res) {
    treeData.value = res.data
    if (!props.currentRow) return
    await nextTick()
    const checked: any[] = []
    eachTree(treeData.value, (v) => {
      if (v.owned) {
        checked.push(v.id)
      }
    })
    defaultCheckedKeys.value = checked
    // eachTree(treeData.value, (v) => {
    //   const index = findIndex(checked, (item) => {
    //     return item.id === v.id
    //   })
    //   if (index > -1) {
    //     const meta = { ...(v.meta || {}) }
    //     meta.permission = checked[index].permission
    //     v.meta = meta
    //   }
    // })
    // for (const item of checked) {
    //   unref(menuTreeRef)?.setChecked(item.id, true, false)
    // }
    // unref(menuTreeRef)?.setCheckedKeys(
    //   checked.map((v) => v.id),
    //   false
    // )
  }
}

const handleClientNodeClick = (data: any) => {
  console.log('Node clicked:', data)
  if (data.id === 999) return
  searchParams.value.clientType = data.id
  console.log('searchParams', clientTreeRef.value!.getCurrentKey())

  getMenuList()
}

const submit = async () => {
  const checkedKeys = unref(menuTreeRef)?.getCheckedKeys() || []
  console.log('checkedKeys', checkedKeys)
  try {
    const res = await sysPermissionSaveRoleResource({
      clientType: unref(searchParams).clientType,
      roleId: props.currentRow?.id,
      resources: checkedKeys
    })
    if (res.code === SUCCESS_CODE) {
      return true
    } else {
      ElMessage.error('保存失败')
      return false
    }
  } catch (error) {
    console.log(error)
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    // setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

onMounted(() => {
  // 设置初始选中的节点
  const nodeData: any = (clientTypeTreeData.length > 0 && getFirstNode(clientTypeTreeData)) || null
  unref(clientTreeRef)?.setCurrentKey(nodeData.id)
  getMenuList()
})

defineExpose({
  submit
})
</script>

<template>
  <Descriptions :schema="detailSchema" :data="currentRow || {}" />
  <div class="flex">
    <div class="w-1/4">
      <ElTree
        ref="clientTreeRef"
        :data="clientTypeTreeData"
        :highlight-current="true"
        :default-expand-all="true"
        node-key="id"
        :props="clientTreeProps"
        @node-click="handleClientNodeClick"
      />
    </div>
    <div class="flex-1">
      <ElTree
        ref="menuTreeRef"
        :data="treeData"
        :show-checkbox="true"
        :highlight-current="true"
        :default-expand-all="true"
        :default-checked-keys="defaultCheckedKeys"
        node-key="id"
        :props="menuTreeProps"
        @node-click="nodeClick"
      />
    </div>
  </div>
</template>
